/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "cmsis_os.h"
#include "adc.h"
#include "dma.h"
#include "i2c.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "delay.h"
#include "mpu6050.h"
#include "rom24c02.h"
#include "w25q.h"
#include "dht11.h"
#include <math.h>
#include <string.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

extern osSemaphoreId binSemLED1Handle;


uint16_t adcValue[2];
uint8_t  keyStatus = 0;
uint8_t  mode = 0;  //0Frequence 1Duty 2Measuer
uint8_t  busy = 0;

uint8_t  freq = 10; //KHz
uint8_t  duty = 50; //%
uint8_t  onOff = 0;

uint32_t period = 0;
short x=0,y=0,z=0;

float AccX=0, AccY=0, AccZ=0;

short Gx=0,Gy=0,Gz=0;
double mean = 0;

uint8_t rom_data[2] = {1,2};

uint16_t over_count = 0;;
uint8_t capture_state = 0; //0 falling  1 rising
uint8_t idx = 0;
uint32_t gap_array[200];
uint32_t pre_captured_val = 0;
uint32_t captured_val = 0;

uint8_t flashBuf[100];
float temparature = 0;
float humidity = 0;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void MX_FREERTOS_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
extern osMessageQId myQueueHandle;
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USART1_UART_Init();
  MX_ADC3_Init();
  MX_TIM2_Init();
  MX_I2C1_Init();
  MX_TIM1_Init();
  MX_SPI1_Init();
  MX_TIM3_Init();
  /* USER CODE BEGIN 2 */
	HAL_TIM_Base_Start(&htim3);
//
	uint8_t  txBuf[15];
	
	//HAL_ADC_Start_DMA(&hadc3, (uint32_t*)adcValue, 2);
	
	//HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_4);
	
  /* USER CODE END 2 */

  /* Call init function for freertos objects (in freertos.c) */
  MX_FREERTOS_Init();

  /* Start scheduler */
  osKernelStart();

  /* We should never get here as control is now taken by the scheduler */
  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
	//delay_init(168);

	while(1) 
	{}
		
	HAL_UART_Receive_IT(&huart1, rxBuf, 2);
	//MPU_Init();
	
	
	HAL_Delay(300);
	ROM_Write_Byte(0, rom_data);
	HAL_Delay(300);
	rom_data[0] = 0;
	rom_data[1] = 0;
	ROM_Read_Byte(0, rom_data+1);
	
	HAL_TIM_Base_Start_IT(&htim1);
	HAL_TIM_IC_Start_IT(&htim1, TIM_CHANNEL_1);
	
//	W25Q_Init();
//	
//	int i=0;
//	for(; i<100; ++i) {
//		flashBuf[i] = i;
//	}
//	W25Q_Write_Page(65535, flashBuf, 100);
//	//W25Q_Chip_Erase();
//	memset(flashBuf, 0, 100 * sizeof(uint8_t));
//	W25Q_Read_Page(65535, flashBuf, 100);
	
	while (1)
  {
		HAL_Delay(300);
		dht11_read(&temparature, &humidity);
	}
	
	
	
	while (1)
  {
		MPU_Get_Accelerometer(&x,&y,&z);
		
		AccX = 2.0 * (x *  (1.0 / 32768.0));
		AccY = 2.0 * (y *  (1.0 / 32768.0));
		AccZ = 2.0 * (z *  (1.0 / 32768.0));		
		
		//double root2 = sqr(2.0);
		mean = sqrt(AccX * AccX + AccY * AccY + AccZ * AccZ);
		HAL_Delay(1);
		MPU_Get_Gyroscope(&Gx, &Gy, &Gz);
		HAL_Delay(1);
	}
  while (1)
  {
		if(keyStatus != 0) {
			busy = 1;
			HAL_GPIO_WritePin(BEEP_GPIO_Port, BEEP_Pin, GPIO_PIN_SET);
			
			if(keyStatus & 0x01) {
				mode++;
				if(mode>2) {
					mode = 0;
				}
				keyStatus &= 0xFE;
				
				txBuf[0] = mode+0x30;
				txBuf[1] = '\n';
				
				HAL_UART_Transmit_IT(&huart1, txBuf, 2);
			}
			
			if(keyStatus & 0x02) {
				if(mode == 0){
					freq += 1;
					if(freq > 20) {
						freq = 20;
					}
				} else if(mode == 1) {
					duty += 5;
					if(duty > 100) {
						duty = 100;
					}
				}
				keyStatus &= 0xFD;
			}
			
			if(keyStatus & 0x04) {
				if(mode == 0){
					freq -= 1;
					if(freq < 1) {
						freq = 1;
					}
				} else if(mode == 1) {
					duty -= 5;
					if(duty < 5) {
						duty = 5;
					}
				}
				keyStatus &= 0xFB;
			}
						
			if(keyStatus & 0x08) {
				onOff++;
				keyStatus &= 0xF7;
			}
			
			period = 2000000/((uint32_t)freq * 1000);
			__HAL_TIM_SET_AUTORELOAD(&htim2, period);
			__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_4, (uint32_t)((duty * 0.01f) * period));
			
			if(onOff%2) {
				txBuf[11] = ' ';
				txBuf[12] = 'o';
				txBuf[13] = 'n';
				HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_4);
			} else {
				txBuf[11] = 'o';
				txBuf[12] = 'f';
				txBuf[13] = 'f';
				HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_4);
			}
			
			HAL_Delay(50);
			HAL_GPIO_WritePin(BEEP_GPIO_Port, BEEP_Pin, GPIO_PIN_RESET);
			HAL_Delay(50);
			
			txBuf[0] = (freq / 10) + 0x30;
			txBuf[1] = (freq % 10) + 0x30;
			txBuf[2] = 'k';
			txBuf[3] = 'H';
			txBuf[4] = 'z';
			txBuf[5] = ',';
			
			
			txBuf[6] = (duty / 100) + 0x30;
			txBuf[7] = ((duty % 100)/10) + 0x30;
			txBuf[8] = ((duty % 100)%10) + 0x30;
			txBuf[9] = '%';
			txBuf[10] = ',';
			txBuf[14] = '\n';
			
			
			HAL_UART_Transmit_IT(&huart1, txBuf, 15);
			
			busy = 0;
		}
		

		//delay_ms(500);
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 4;
  RCC_OscInitStruct.PLL.PLLN = 168;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
	if(busy) {
		return;
	}
	idx = 0;
	memset(gap_array, 0, sizeof(uint32_t) * 200);
	
	//HAL_GPIO_TogglePin(LED_2_GPIO_Port, LED_2_Pin);
	
	uint16_t info = 200;
	osMessagePut(myQueueHandle, (uint32_t)info, osWaitForever);
	
	osSemaphoreRelease(binSemLED1Handle);
	
	if(HAL_GPIO_ReadPin(Key_Function_GPIO_Port, Key_Function_Pin) == GPIO_PIN_RESET ) 
	{
		keyStatus |= 0x01;
	}
	
	if(HAL_GPIO_ReadPin(Key_Add_GPIO_Port, Key_Add_Pin) == GPIO_PIN_RESET ) 
	{
		keyStatus |= 0x02;
	}
	
	if(HAL_GPIO_ReadPin(Key_Minus_GPIO_Port, Key_Minus_Pin) == GPIO_PIN_RESET ) 
	{
		keyStatus |= 0x04;
	}
	
	if(HAL_GPIO_ReadPin(Key_OnOff_GPIO_Port, Key_OnOff_Pin) == GPIO_PIN_RESET ) 
	{
		keyStatus |= 0x08;
	}
	
	
}


void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
	captured_val = HAL_TIM_ReadCapturedValue(&htim1, TIM_CHANNEL_1);
	
	if(over_count > 0) {
		captured_val = (65535 - pre_captured_val) + captured_val + (over_count - 1) * 65535;
	} else {
		captured_val = captured_val - pre_captured_val;
	}
	
	over_count = 0;
	gap_array[idx] = captured_val;
	idx++;
	
	pre_captured_val = HAL_TIM_ReadCapturedValue(&htim1, TIM_CHANNEL_1);
	
	if(capture_state == 0) {
		__HAL_TIM_SET_CAPTUREPOLARITY(&htim1, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_RISING);
		capture_state = 1;
	} else	if(capture_state == 1) {
		__HAL_TIM_SET_CAPTUREPOLARITY(&htim1, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_FALLING);
		capture_state = 0;
	}

}

/* USER CODE END 4 */

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM7 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM7) {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */

  /* USER CODE END Callback 1 */
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
